package com.weixx.shiro.controller;


import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@Controller
public class ShiroController {

    @RequestMapping({"/","/index"})
    public String toIndex(Model model){
        model.addAttribute("msg","hello,shiro");
        return "index";

    }
    @RequestMapping({"/add"})
    public String toAdd(){
        return "add";

    }
    @RequestMapping({"/update"})
    public String toUpdate(){
        return "update";

    }
    @RequestMapping({"/toLogin"})
    public String toLogin(){
        return "login";

    }
    @RequestMapping({"/loginout"})
    public String loginout(){
        Subject currentUser = SecurityUtils.getSubject();
        currentUser.logout();
        return "login";

    }
    //认证失败返回
    @RequestMapping({"/loginfaile"})
    @ResponseBody
    public String loginfail(){
        return "用户未授权";

    }

    @RequestMapping({"/gotoLogin"})
    public String login(String username,String password,Model model){
        //获取当前的用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登录数据
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
        try {
            subject.login(usernamePasswordToken);
        }catch (UnknownAccountException e){
            model.addAttribute("msg","用户名错误");
        }catch (IncorrectCredentialsException e){
            model.addAttribute("msg","密码错误");
        }
        return "index";

    }

}
